Hello大家好 👋 相信這個周末看到好幾個知名大公司都陸續被駭客攻擊的新聞後,就可以知道安全性真的很重要,所以我們今天就來跟大家介紹怎麼應用Spring security來協助我們進行各種認證(authentication)與授權(authorization)的控管
pom.xml
新增dependency <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
config
的資料夾,這樣可以將我們針對application設定的config都放在該資料夾中@EnableWebSecurity
和 @Configuration
,這樣我們就可以讓我們的Application套用這個設定import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(new Customizer<AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry>() {
@Override
public void customize
(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorizationManagerRequestMatcherRegistry) {
authorizationManagerRequestMatcherRegistry
//指定上述匹配規則中的url,允許所有用戶接可以訪問,不需要進行身份驗證
.requestMatchers("/internal/**").permitAll()
//需要身分驗證的路徑
.requestMatchers("/external/**").authenticated();
}
})
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
httpBasic()
接著我們可以依照上面設定的url來建立看看API,並用postman測試結果
@GetMapping("internal/hello")
public ResponseEntity<String> testHello() {
return ResponseEntity.ok("Hello World !!!");
}
@GetMapping("external/hello")
public ResponseEntity<String> testHello() {
return ResponseEntity.ok("Hello World !!!");
}
這樣我們就輕鬆完成最簡易的安全配置了,明天我們在繼續